package com.ruoyi.web.controller.h5;

import java.math.BigDecimal;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import javax.servlet.http.HttpServletResponse;
import org.springframework.security.access.prepost.PreAuthorize;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.model.StylesTable;
import org.apache.poi.xssf.usermodel.XSSFCellStyle;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.apache.poi.ss.util.CellRangeAddress;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.exception.user.UserException;
import com.ruoyi.web.domain.UserOrder;
import com.ruoyi.web.domain.UserOrderDetail;
import com.ruoyi.web.domain.UserSettlement;
import com.ruoyi.web.service.IUserOrderDetailService;
import com.ruoyi.web.service.IUserOrderService;
import com.ruoyi.web.service.IUserSettlementService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;

/**
 * 结算单Controller
 * 
 * @author ruoyi
 * @date 2025-06-11
 */
@RestController
@RequestMapping("/h5/settlement")
public class H5UserSettlementController extends BaseController
{
    @Autowired
    private IUserSettlementService userSettlementService;

    @Autowired
    private IUserOrderService userOrderService;

    @Autowired
    private IUserOrderDetailService userOrderDetailService;
    /**
     * 查询结算单列表
     */
    @GetMapping("/list")
    public TableDataInfo list(UserSettlement userSettlement)
    {
        startPage();
        List<UserSettlement> list = userSettlementService.selectUserSettlementList(userSettlement);
        return getDataTable(list);
    }

    /**
     * 获取结算单详细信息
     */
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        UserSettlement userSettlement = userSettlementService.selectUserSettlementById(id);
        List<UserOrder> userOrder =  userOrderService.selectUserOrdeByIds(userSettlement.getOrderIds());
        Map<String, Object> result = new HashMap<>();
        result.put("settlement", userSettlement);
        result.put("orders", userOrder);
        
        return success(result);
    }

    /**
     * 新增结算单
     */
    @Log(title = "结算单", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody UserSettlement userSettlement)
    {
        // 将逗号分隔的订单ID字符串转换为Long数组
        Long[] orderIds = userSettlement.getOrderIds();
        int rows2 = userSettlementService.insertUserSettlement(userSettlement);
        int rows = 0;
        if(rows2>0){
            rows = userOrderService.updateUserOrderIsSettlementByOrderIds(orderIds, "2");
        }
        return toAjax(rows2);
    }

    /**
     * 修改结算单
     */
    @Log(title = "结算单", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody UserSettlement userSettlement)
    {
        return toAjax(userSettlementService.updateUserSettlement(userSettlement));
    }

    /**
     * 删除结算单
     */
    @Log(title = "结算单", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        return toAjax(userSettlementService.deleteUserSettlementByIds(ids));
    }

    /**
     * 导出销售详情列表
     */
    @Log(title = "结算订单详情", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, @RequestBody UserSettlement userSettlement)
    {
        List<UserSettlement> list = userSettlementService.selectUserSettlementList(userSettlement);
        List<UserOrder> userOrder =  userOrderService.selectUserOrdeByIds(list.get(0).getOrderIds());
        Long[] ids = userOrder.stream()
                    .map(UserOrder::getId)
                    .toArray(Long[]::new);
        List<UserOrderDetail> detailList = userOrderDetailService.selectUserOrderDetailByOrderIds(ids);
        userOrder.forEach(item -> {
            item.setDetailList(detailList.stream().filter(detail -> detail.getOrderId().equals(item.getId())).collect(Collectors.toList()));
        });
        list.get(0).setDetail(userOrder);

        Workbook workbook = new XSSFWorkbook();
        Sheet sheet = workbook.createSheet("结算单详情");

        // 表头
        Row header = sheet.createRow(0);
        header.createCell(0).setCellValue("订单日期");
        header.createCell(1).setCellValue("签名地址");
        header.createCell(2).setCellValue("商品名称");
        header.createCell(3).setCellValue("商品规格");
        header.createCell(4).setCellValue("商品数量");
        header.createCell(5).setCellValue("商品单价");
        header.createCell(6).setCellValue("总额");
        // 创建居中样式
        CellStyle centerStyle = workbook.createCellStyle();
        centerStyle.setAlignment(HorizontalAlignment.CENTER);
        centerStyle.setVerticalAlignment(VerticalAlignment.CENTER);
        int maxColumnWidth = 20 * 256; // 80字符宽度
        // 设置表头样式
        for (int i = 0; i <= 6; i++) {
            // sheet.autoSizeColumn(i);
            Cell cell = header.getCell(i);
            if (cell != null) {
                cell.setCellStyle(centerStyle);
            }
            sheet.setColumnWidth(i, maxColumnWidth);
        }
        int rowNum = 1;
        BigDecimal amount = BigDecimal.ZERO;
        for (UserOrder order : userOrder) {
            List<UserOrderDetail> details = order.getDetailList();
            int detailSize = details.size();

            if (detailSize == 0) {
                // 没有详情时也输出一行
                Row row = sheet.createRow(rowNum);
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                row.createCell(0).setCellValue(sdf.format(order.getDate()));
                row.createCell(1).setCellValue(order.getSign());
                row.createCell(2).setCellValue("");
                row.createCell(3).setCellValue("");
                row.createCell(4).setCellValue("");
                row.createCell(5).setCellValue("");
                row.createCell(6).setCellValue("");
                amount = amount.add(BigDecimal.ZERO);
                rowNum++;
            } else {
                for (int i = 0; i < detailSize; i++) {
                    Row row = sheet.createRow(rowNum + i);
                    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                    row.createCell(0).setCellValue(sdf.format(order.getDate()));
                    row.createCell(1).setCellValue(order.getSign());
        
                    UserOrderDetail detail = details.get(i);
                    row.createCell(2).setCellValue(detail.getShopName());
                    row.createCell(3).setCellValue(detail.getShopSpec());
                    row.createCell(4).setCellValue(detail.getShopNumber());
                    row.createCell(5).setCellValue(detail.getShopPrice().toString());
                    row.createCell(6).setCellValue(detail.getShopAmount().toString());
                    amount = amount.add(detail.getShopAmount());
                }
                // 合并单元格
                if (detailSize > 1) {
                    // 合并订单日期
                    sheet.addMergedRegion(new CellRangeAddress(rowNum, rowNum + detailSize - 1, 0, 0));
                    // 合并签名地址
                    sheet.addMergedRegion(new CellRangeAddress(rowNum, rowNum + detailSize - 1, 1, 1));
                }
                rowNum += detailSize;
            }
            
        }
        Row row = sheet.createRow(rowNum);
        row.createCell(0).setCellValue("总计：");
        row.createCell(6).setCellValue(Float.parseFloat(amount.toString()));
        sheet.setDefaultRowHeight((short) 600);
        // 可选：合并"总计"单元格（让"总计"横跨0~5列）
        sheet.addMergedRegion(new CellRangeAddress(rowNum, rowNum, 0, 5));
        try {
            
            String fileName = URLEncoder.encode("结算单详情.xlsx", "UTF-8");
            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
            response.setHeader("Content-Disposition", "attachment;filename=" + fileName);
            workbook.write(response.getOutputStream());
            workbook.close();
        } catch (Exception e) {
            // TODO: handle exception
            throw new UserException("settlement.init.error", null);
        }
    }
}
